package com.ajx.blog.controller;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import com.ajx.blog.entity.Article;
import com.ajx.blog.entity.ArticleComment;
import com.ajx.blog.entity.Blogusers;
import com.ajx.blog.entity.ContentType;
import com.ajx.blog.entity.FocusInfo;
import com.ajx.blog.service.api.*;
import com.ajx.blog.entity.*;
import com.ajx.blog.util.OnloadUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;

import org.apache.dubbo.config.annotation.Reference;
import org.json.JSONString;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping("/blog/user")
public class BlogusersController {

    private Logger logger = LoggerFactory.getLogger(BlogusersController.class);

    @Reference(url = "dubbo://localhost:20880")
    private ArticleDistributeService articleDistributeService;

    @Reference(url = "dubbo://localhost:20881", timeout = 2000)
    private UserService userService;

    @Reference(url = "dubbo://localhost:20881", timeout = 2000)
    private BlogusersService blogusersService;

    @Reference(url = "dubbo://localhost:20883", timeout = 2000)
    private ContentTypeService contentTypeService;

    @Reference(url = "dubbo://localhost:20883", timeout = 2000)
    private ArticleService articleService;

    @Reference(url = "dubbo://localhost:20883", timeout = 2000)
    private ArticleCheckMessageService articleCheckMessageService;

    @Reference(url = "dubbo://localhost:20881", timeout = 2000)
    private FocusInfoService focusInfoService;

    @Reference(url = "dubbo://localhost:20883", timeout = 2000)
    private ArticleCollInfoService articleCollInfoService;

    @Reference(url = "dubbo://localhost:20883", timeout = 2000)
    private ArticleCommentService articleCommentService;

    @RequestMapping("/comment")
    public String comment(Model model, Integer aid) {
        // aid是文章id blogID是 根据文章获取评1论
        logger.info("跳转到添加评论页面");
        // 获取一级评论
        List<ArticleComment> cList = articleService.selectArticle(aid);
        // 获取二级评论
        Map<Integer, List<ArticleComment>> secondMap = articleCommentService.selectBackComment();
        // 获取文章对象
        Article article = articleService.selectbyId(aid);
        model.addAttribute("articleList", article);
        model.addAttribute("secondMap", secondMap);
        model.addAttribute("cList", cList);
        return "blog_comment";
    }

    @RequestMapping("/ucomment")
    @ResponseBody
    public Object addRecords(HttpSession session, ArticleComment articleComment) {
        Map<String, Object> map = new HashMap<>();
        if (session.getAttribute("u") != null) {
            if (articleService.addComment(articleComment)) {// 方法返回true
                map.put("code", 0);
                map.put("msg", "评论成功");
                return map;
            } else {// 方法返回false
                map.put("code", -1);
                map.put("msg", "评论失败");
                return map;
            }
        } else {
            map.put("code", -1);
            map.put("msg", "请先登录,在评论！！！");
            return map;
        }
    }

    /**
     * 用户注册的方法
     *
     * @param blogusers 用户实例
     * @return 返回注册信息
     */
    @RequestMapping("register")
    @ResponseBody
    public String userRegister(Blogusers blogusers) {
        logger.info("调用了用户登录的方法");
        if (userService.addUser(blogusers) == 1) {
            return JSONArray.toJSONString("注册成功");
        }
        return JSONArray.toJSONString("注册失败");
    }

    /**
     * 用户进入主页显示信息
     *
     * @return 文章信息
     */
    @RequestMapping("login")
    public String userLogin(HttpSession session) {
        String name = SecurityContextHolder.getContext()
                .getAuthentication().getName();
        Blogusers blogusers = userService.userLoginByName(name);
        System.out.println(blogusers);
        session.setAttribute("u", blogusers);
        return "index";
    }

    /**
     * 用户进入主页显示信息
     *
     * @return 文章信息
     */
    @RequestMapping("index")
    @ResponseBody
    public Map<String, Object> UserIndex(HttpSession session) {
        // 根据时间查询出最近的十条文章记录
        HashMap<String, Object> hashMap = new HashMap<>();
        List<ContentType> contentTypes = contentTypeService.selectAllType();
        Blogusers u = (Blogusers) session.getAttribute("u");
        List<Article> articlesByDate = null;
        if (u != null) {
            // 查询最近十条文章
            Map<String, Object> stringIntegerMap = new HashMap<>();
            stringIntegerMap.put("limit", 9);
            stringIntegerMap.put("uid", u.getUid());
            articlesByDate = articleService.selectByExamples(stringIntegerMap);
            for (ContentType type : contentTypes) {
                Map<String, Object> stringIntegerMap1 = new HashMap<>();
                stringIntegerMap1.put("uid", u.getUid());
                stringIntegerMap1.put("typeid", type.getCid());
                stringIntegerMap1.put("limit", 4);
                List<Article> articles = articleService.selectByExamples(stringIntegerMap1);
                hashMap.put(String.valueOf(type.getCid()), articles);
            }
        } else {
            Article article = new Article();
            articlesByDate = articleService.selectByExample(article);
            for (ContentType type : contentTypes) {
                article.setTypeid(type.getCid());
                List<Article> articles = articleService.selectByExample(article);
                hashMap.put(String.valueOf(type.getCid()), articles);
            }

        }
        hashMap.put("artclesByDate", articlesByDate);
        hashMap.put("blogType", contentTypes);
        return hashMap;
    }

    /**
     * 用户添加文章的方法
     *
     * @param article 文章实例
     * @param imgUrl  文章图片
     * @return 返回路径
     */
    @RequestMapping("add.do")
    @ResponseBody
    public Map<String, Object> addArticle(Article article, MultipartFile imgUrl, HttpSession session) {
        logger.info("调用用户添加文章的方法");
        HashMap<String, Object> result = new HashMap<>();
        try {
            Blogusers u = (Blogusers) session.getAttribute("u");
            article.setBloguid(u.getUid());
            article.setAstatus("0");
            article.setArtimg(OnloadUtil.uploadFile(imgUrl));
            int i = articleService.addArticle(article);
            if (i != -1) {
                if (articleDistributeService.assigningTask(i)) {
                    result.put("code", 1);
                    result.put("msg", "文章添加成功");
                } else {
                    result.put("code", 0);
                    result.put("msg", "审核员分配失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            result.put("code", 0);
            result.put("msg", "图片保存出现异常");
        }
        return result;
    }

    /**
     * 用户查看自己所有文章信息的方法
     *
     * @param pageNum  当前页
     * @param pageSize 每页显示记录条数
     * @param session  获取用户信息
     * @return 返回分页后的文章信息
     */
    @RequestMapping("userArticle")
    @ResponseBody
    public Map<String, Object> selectUserArticle(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize, HttpSession session) {
        logger.info("根据用户信息返回用户文章");
        Blogusers u = (Blogusers) session.getAttribute("u");
        // 根据用户id 查询所有博客信息的方法
        QueryWrapper<Article> qw = new QueryWrapper<>();
        qw.eq("bloguid", u.getUid()).orderByAsc("astatus");
        PageInfo<Article> articles = articleService.selectPgeInfoByQW(qw, pageNum, pageSize);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("pages", articles);
        return stringObjectHashMap;
    }

    // 用户修改博客信息的方法
    @RequestMapping("update.do")
    public String updateArticle(Article article, HttpSession session, MultipartFile imgUrl) {
        logger.info("用户修改文章信息的方法");
        Blogusers u = (Blogusers) session.getAttribute("u");
        article.setBloguid(u.getUid());
        article.setAstatus("0");
        try {
            if (imgUrl != null) {
                String s = OnloadUtil.uploadFile(imgUrl);
                article.setArtimg(s);
            }
            if (articleService.updateArticle(article)) {
                Boolean aBoolean = articleDistributeService.assigningTask(article.getAid());
                return "ain_articleList";
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    @RequestMapping("collect")
    @ResponseBody
    public String collect(Integer aid, HttpSession session) {
        logger.info("收藏文章");
        Blogusers u = (Blogusers) session.getAttribute("u");
        Integer uid = u.getUid();
        if (articleService.collect(aid, uid) > 0) {
            return JSONArray.toJSONString("收藏成功");
        } else {
            return JSONArray.toJSONString("收藏失败");
        }
    }

    // 跳转到文章作者信息关注页面
    @RequestMapping("articlelist")
    public String articleList(Integer bloguid, HttpSession session, Model model) {
        logger.info("获取用户写的文章并查找用户的信息集合");
        // 查询博主写的文章
        Blogusers u = (Blogusers) session.getAttribute("u");
        boolean bb = focusInfoService.selectExsit(u.getUid(), bloguid);
        Article article = new Article();
        article.setBloguid(bloguid);
        List<Article> articleList = articleService.selectByExample(article);
        List<FocusInfo> focusInfoList = focusInfoService.selectTargetUid(bloguid);
        Blogusers blogusers = blogusersService.selectBlogusers(bloguid);
        int size1 = focusInfoList.size();
        int size = articleList.size();
        int num = 0;
        for (Article a : articleList) {
            int num1 = a.getCollnum();
            num += num1;
        }
        model.addAttribute("exsit", bb);
        // 获取文章作者信息
        model.addAttribute("blogusers", blogusers);
        // 遍历文章
        model.addAttribute("articleList", articleList);
        // 文章总数
        model.addAttribute("size", size);
        // 收藏总数
        model.addAttribute("num", num);
        // 关注总数
        model.addAttribute("size1", size1);
        return "collection";
    }

    // 模糊查询博客信息的方法
    @RequestMapping("likeSelect")
    @ResponseBody
    public Map<String, Object> selectLikeArticle(@RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "10") Integer pageSize, @RequestParam(required = true) String keywords,
            @RequestParam(required = true) Integer typeId) {

        QueryWrapper<Article> articleQueryWrapper = new QueryWrapper<>();
        if (typeId != null) {
            articleQueryWrapper.eq("typeid", typeId).like("keywords", keywords);
        } else {
            articleQueryWrapper.like("keywords", keywords);
        }
        PageInfo<Article> articlePageInfo = articleService.selectPgeInfoByQW(articleQueryWrapper, pageNum, pageSize);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("pages", articlePageInfo);
        return stringObjectHashMap;
    }

    /**
     * 跳转到添加文章页面
     *
     * @param model 商品类型数据
     * @return 添加商品页面
     */
    @RequestMapping("add.to")
    @ResponseBody
    public Map<String, Object> toAddArticle(Model model) {

        List<ContentType> contentTypes = contentTypeService.selectAllType();
        model.addAttribute("type", contentTypes);
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("types", contentTypes);
        return stringObjectHashMap;
        // return "article-add";

    }

    @RequestMapping("update.to")
    public String toUpdateArticle(Model model, @RequestParam(required = false) Integer aid) {
        List<ContentType> contentTypes = contentTypeService.selectAllType();
        model.addAttribute("type", contentTypes);
        Article article = articleService.selectbyId(aid);
        model.addAttribute("article", article);
        return "article-update";

    }

    /**
     * 去文章页面
     *
     * @param model 数据
     * @return 页面路劲
     */
    @RequestMapping("article.to")
    public String toArticle(Model model, HttpSession session) {
        // 获取最热文章
        List<Article> articles = articleService.selectHottest();
        model.addAttribute("hottestArticle", articles);
        List<ContentType> contentTypes = contentTypeService.selectAllType();
        model.addAttribute("type", contentTypes);
        if (session.getAttribute("u") == null) {
            // 获取所有文章类型

            // 获取最新文章
            Map<String, Object> stringStringMap = new HashMap<>();
            stringStringMap.put("orderBy", "createtime desc");
            stringStringMap.put("limit", "limit 4");
            List<Article> articles1 = articleService.selectByMap(stringStringMap);
            model.addAttribute("newArticle", articles1);

        } else {
            Blogusers u = (Blogusers) session.getAttribute("u");
            Map<String, Object> stringIntegerMap = new HashMap<>();
            stringIntegerMap.put("limit", 4);
            stringIntegerMap.put("uid", u.getUid());
            List<Article> articlesByDate = articleService.selectByExamples(stringIntegerMap);
            model.addAttribute("newArticle", articlesByDate);
        }
        return "article";
    }

    @RequestMapping("article.do")
    @ResponseBody
    public Map<String, Object> doArticle(@RequestParam(required = false) Integer typeId,
            @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "5") Integer pageSize) {
        System.out.println(typeId);
        Article article = new Article();
        article.setTypeid(typeId);
        System.out.println(pageSize);
        List<Article> list = articleService.selectByExample(article);

        PageInfo<Article> articlePageInfo = articleService.selectPageInfoByEample(article, pageNum, pageSize);
        System.out.println(articlePageInfo);
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("pages", articlePageInfo);
        return stringObjectMap;
    }

    // 添加关注
    @RequestMapping("concern")
    public String Concern(HttpSession session, Integer bloguid, Model model) {
        logger.info("添加关注");
        Blogusers u = (Blogusers) session.getAttribute("u");
        Integer uid = u.getUid();
        focusInfoService.addConcern(bloguid, uid);
        model.addAttribute("bloguid", bloguid);
        return "redirect:/blog/user/articlelist?bloguid=" + bloguid;
    }

    // 查询用户自己的文章
    @RequestMapping("ainarticle")
    @ResponseBody
    public Map<String, Object> ainArticle(HttpSession session, Model model,
            @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "8") Integer pageSize) {
        logger.info("查询用户自己的文章");
        Blogusers u = (Blogusers) session.getAttribute("u");
        Integer uid = u.getUid();
        // 根据用户查询文章
        HashMap<Integer, Object> map = new HashMap<>();
        Map<String, Object> stringObjectMap = new HashMap<>();
        stringObjectMap.put("bloguid", u.getUid());
        stringObjectMap.put("orderBy", "astatus");
        PageInfo<Article> articleListPageInfo = articleService.selectByMapPageInfo(stringObjectMap, pageNum, pageSize);
        List<Article> articleList = articleService.selectArticleList(uid);
        for (Article aid : articleListPageInfo.getList()) {
            if (aid.getAstatus().equals("-1")) {
                Integer aid1 = aid.getAid();
                ArticleCheckMessage cmList = articleCheckMessageService.selectArticleCheckMessage(aid1);
                System.out.println(aid1);
                System.out.println(cmList);
                map.put(aid1, cmList);
            }
            // 根据文章id查询被驳回的意见
        }
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("pages", articleListPageInfo);
        stringObjectHashMap.put("cmList", map);
        model.addAttribute("articleList", articleListPageInfo);
        model.addAttribute("cmList", map);
        return stringObjectHashMap;
        // return "ain_articleList";

    }

    @RequestMapping("/add.do01")
    @ResponseBody
    public Map<String, Object> addsArticle(MultipartFile imgUrl, Article article) {
        Map<String, Object> stringObjectMap = new HashMap<>();
        try {
            String s = OnloadUtil.uploadFile(imgUrl);
            article.setAstatus("0");
            article.setArtimg(s);
            int i = articleService.addArticle(article);
            Boolean aBoolean = articleDistributeService.assigningTask(i);

            stringObjectMap.put("msg", "添加成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        stringObjectMap.put("msg", "上传失败");
        return stringObjectMap;
    }

    @RequestMapping("exits")
    @ResponseBody
    public Boolean exist(HttpSession session) {
        if ((Blogusers) session.getAttribute("u") != null) {
            return true;
        }
        return false;
    }

    @RequestMapping("myconcern")
    @ResponseBody
    public Map<String, Object> myconcern(HttpSession session, Model model,
            @RequestParam(defaultValue = "1") Integer pageNum) {
        logger.info("查询用户自己的关注的文章");
        Blogusers u = (Blogusers) session.getAttribute("u");
        Integer uid = u.getUid();
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        stringObjectHashMap.put("pages", articleCollInfoService.selectArticleCollInfo(uid, pageNum));
        return stringObjectHashMap;
    }

    /**
     * @param cid
     * @return java.lang.String
     *         pid 就是 cid
     * @date: 2022/4/22 16:22
     * @author 刘振升
     * @description: 回复消息
     */
    @RequestMapping("backcomment")
    public String backComment(HttpSession session, Integer cid, String content) {
        logger.info("添加回复字段");
        Blogusers u = (Blogusers) session.getAttribute("u");
        Integer uid = u.getUid();
        if (articleCommentService.addBackComment(cid, uid, content) > 0) {
            return JSONArray.toJSONString("回复成功！");
        } else {
            return JSONArray.toJSONString("回复失败！");
        }

    }

}